//
//  EmoticonPackage.swift
//  表情键盘
//
//  Created by MACBOOK on 16/10/16.
//  Copyright © 2016年 刘袭锐. All rights reserved.
//

import UIKit

class EmoticonPackage: NSObject {
    //FIXME: 表情
    var emoticons : [Emoticon] = [Emoticon]()
    
    //FIXME: 重写构造方法
    init(id : String) {
        super.init()
        
        // 1.最近分组
        if id == "" {
            addEmptyEmotion(true)
            return
        }
        
        // 2.根据id拼接info.plist的路径
        let plistPath = Bundle.main.path(forResource: "\(id)/info.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        
        // 3.根据plist文件的路径读取数据 [[String : String]]
        let array = NSArray(contentsOfFile: plistPath)! as! [[String : String]]
        
        // 4.遍历数组
        var index = 0 //添加删除按钮记录
        
        for var dict in array {
            if let png = dict["png"] {
                // 拼接Png路径
                dict["png"] = id + "/" + png
            }
            
            emoticons.append(Emoticon(dict: dict))
            index += 1
            
            if index == 20 {
                // 添加删除按钮
                emoticons.append(Emoticon(isRemove : true))
                index = 0
            }
        }
        
        // 5.添加空白表情
        addEmptyEmotion(false)
        
    }
    
    //FIXME: 添加空白表情
    fileprivate func addEmptyEmotion(_ isRecently : Bool){
        let count = emoticons.count % 21
        if count == 0 && !isRecently {
            return
        }
        
        for _ in count..<20 {
            emoticons.append(Emoticon(isEmpty: true))
        }
        
        emoticons.append(Emoticon(isRemove: true))
        
    }
}
